//
//  NSObject+LILDealloc.m
//  LILDeallocKVO
//
//  Created by LL on 2022/7/22.
//

#import "NSObject+LILDealloc.h"

#import <objc/runtime.h>

@interface LILDeallocKVO : NSObject

@property (nonatomic, copy) void (^deallocBlock)(void);

@end

@implementation LILDeallocKVO

- (void)dealloc {
    !self.deallocBlock ?: self.deallocBlock();
}

@end



@interface NSObject ()

@property (nonatomic, strong, nullable) LILDeallocKVO *deallocObject;

@end

@implementation NSObject (LILDealloc)

- (void)KVODealloc:(void (^ _Nullable)(void))block {
    LILDeallocKVO *deallocObject = [[LILDeallocKVO alloc] init];
    deallocObject.deallocBlock = block;
    self.deallocObject = deallocObject;
}

- (void)KVODealloc2:(void (^ _Nullable)(id obj))block {
    
}

- (void)setDeallocObject:(LILDeallocKVO *)deallocObject {
    objc_setAssociatedObject(self, @selector(deallocObject), deallocObject, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (LILDeallocKVO *)deallocObject {
    return objc_getAssociatedObject(self, @selector(deallocObject));
}

@end
